<?php


class UserController extends Yaf_Controller_Abstract {

	
	public function loginAction(){
        $request = json_decode(file_get_contents("php://input"),true);
		$where['username= ?'] = $request['username'];
		$model = new AdminModel();
		$admin = $model->getAdmin($where);
		
		if($admin){
			if($admin['password'] == md5($request['password'])){
				echo json_encode(['status'=>'1', 'message'=>'登录成功']);
			}else{
				echo json_encode(['status'=>'0', 'message'=>'密码错误']);
			}
			
		}else{
			echo json_encode(['status'=>'0', 'message'=>'账号不存在']);
		}
	}

	public function getUserListAction(){
		$request=json_decode(file_get_contents("php://input"),true);
		$page = $request['page'] ? $request['page'] : 1;
		$pagesize = $request['pagesize'] ? $request['pagesize'] : 10;

		$where = [];
		
		$model = new UserModel();
		$list = $model->getList($where, $page, $pagesize);
		foreach($list as &$val){
			$val['ctime'] = date('Y-m-d H:i', $val['ctime']);
		}
		$count = $model->count($where);
		
		echo json_encode(['total' => $count, 'list' => $list]);
	}
	
	public function getUserAction(){
		$request = json_decode(file_get_contents("php://input"),true);
		$id = $request['id'];
		
		$model = new UserModel();
		$where = [];
		if($id){
			$where['id = ?'] = $id;
		}
		
		$rs = $model->getOne($where);
		
		echo json_encode($rs);
	}
	
	public function saveUserAction(){
		$request = json_decode(file_get_contents("php://input"),true);
		if(!$request) return;
		$model = new UserModel();

		$data = [
			'username' => $request['username'],
			'mobile'   => $request['mobile'],
			'head'     => $request['head'],
			'address'  => $request['address'],
			'integral' => $request['integral'],
			'balance'  => $request['balance'],
		];
		if($request['id']){
			$where['id = ?'] = $request['id'];
			
			$rs = $model->save($data, $where);
		}else{
			$rs = $model->add($data);
		}
		echo json_encode($rs);
	}
}
